package com.hqd.ch03.v46.core.type.classreading;

import com.hqd.ch03.v46.core.NestedIOException;
import com.hqd.ch03.v46.core.type.AnnotationMetadata;
import com.hqd.ch03.v46.core.type.ClassMetadata;
import com.hqd.ch03.v46.io.Resource;
import org.objectweb.asm.ClassReader;

import java.io.IOException;
import java.io.InputStream;

final class SimpleMetadataReader implements MetadataReader {

    private static final int PARSING_OPTIONS = ClassReader.SKIP_DEBUG
            | ClassReader.SKIP_CODE | ClassReader.SKIP_FRAMES;

    private Resource resource;

    private AnnotationMetadata annotationMetadata;


    SimpleMetadataReader(Resource resource, ClassLoader classLoader) throws IOException {
//        SimpleAnnotationMetadataReadingVisitor visitor = new SimpleAnnotationMetadataReadingVisitor(classLoader);
//        getClassReader(resource).accept(visitor, PARSING_OPTIONS);
//        this.resource = resource;
//        this.annotationMetadata = visitor.getMetadata();
    }

    @SuppressWarnings("deprecation")
    private static ClassReader getClassReader(Resource resource) throws IOException {
        try (InputStream is = resource.getInputStream()) {
            try {
                return new ClassReader(is);
            } catch (IllegalArgumentException ex) {
                throw new NestedIOException("ASM ClassReader failed to parse class file - " +
                        "probably due to a new Java class file version that isn't supported yet: " + resource, ex);
            }
        }
    }


    @Override
    public Resource getResource() {
        return this.resource;
    }

    @Override
    public ClassMetadata getClassMetadata() {
        return this.annotationMetadata;
    }

    @Override
    public AnnotationMetadata getAnnotationMetadata() {
        return this.annotationMetadata;
    }

}